#include "type.h"

void main(int argc, char* argv[])
{
	int fd = -1, bytesRead = 0;
	char *file;
	
	do_write(2, "*****************************\n\r", 31);
	do_write(2, "*      JRR Cat Program      *\n\r", 31);
	do_write(2, "*****************************\n\r", 31);
	
	if (argc == 1)
	{
		if (contains(' ', argv[0]))
		{
			strtok(argv[0], " ");
			file = argv[0] + strlen(argv[0]) + 1;
			fd = open(file, READ);
			do_write(2, "Reading from \"", 14);
			do_write(2, file, strlen(file));
			do_write(2, "\"\n\r", 3);
		}
		else // Read from stdin
		{
			fd = 0;
			do_write(2, "Reading from stdin\n\r", 20);
		}
	}
	else if (argc == 2)
	{
		strncpy(file, argv[1], strlen(argv[1]) - 1);
		fd = open(argv[1], READ);
		do_write(2, "Reading from \"", 14);
		do_write(2, argv[1], strlen(argv[1]));
		do_write(2, "\"\n\r", 3);
	}
	else
	{
		printf("Usage: cat filename\n");
		return;
	}
	
	// Do the cat operation			
	if (fd > -1)
	{
		char buf;
		do
		{
			bytesRead = do_read(fd, &buf, 1);
			do_write(1, &buf, bytesRead);
			if (buf == '\n')
			{
				buf = '\r';
				do_write(1, &buf, 1);
			}
		} while (bytesRead == 1);
	}
	else
	{
		printf("Unable to open \"%s\"!\n", file);
	}
}
